#pragma once
#include <condition_variable>
#include <mutex>
class Semaphore {
public:
    Semaphore(int resourceLimit = 0) : res_(resourceLimit) {
    }
    ~Semaphore() = default;

    Semaphore(const Semaphore&) = delete;
    Semaphore& operator=(const Semaphore&) = delete;

    void wait() {
        std::unique_lock<std::mutex> lock(mtx_);
        cv_.wait(lock, [&]() -> bool { return res_ > 0; });
        res_--;
    }

    void post() {
        std::unique_lock<std::mutex> lock(mtx_);
        res_++;
        cv_.notify_all();
    }

private:
    int res_;  // 当前可用资源数
    std::mutex mtx_;
    std::condition_variable cv_;
};
